package cn.edu.fzu.homemaking.filter;

import cn.edu.fzu.homemaking.api.SsoApi;
import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.exception.ServiceException;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Objects;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Order(2)
@WebFilter(urlPatterns = "/api/order/auth/*")
public class AuthFilter implements Filter {

    @Value("${allow.ip}")
    private String                    allowedIPs;

    @Resource
    private SsoApi ssoApi;

    @Override
    public void init(FilterConfig filterConfig) {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        resp.setHeader("content-type", "application/json");
        resp.setHeader("charset", "UTF-8");

        if (!allowedIPs.contains(getIp(req))) {
            return;
        }
        Result type = ssoApi.getSession(SessionConstant.USER_TYPE);
        Result user = ssoApi.getSession(SessionConstant.ACCOUNT);
        Long customerId = null;
        Long companyId = null;
        if(Objects.equal((String)type.getValue(), SessionConstant.USER)){
            Long id = ((JSONObject) user.getValue()).getLong("customerId");
            customerId = id;
        }else if (Objects.equal((String)type.getValue(), SessionConstant.COMPANY)){
            Long id = ((JSONObject) user.getValue()).getJSONObject("company").getLong("id");
            companyId = id;
        }
        req.getSession().setAttribute(SessionConstant.USER, customerId);
        req.getSession().setAttribute(SessionConstant.COMPANY,companyId);
        req.getSession().setAttribute(SessionConstant.USER_TYPE,type.getValue());
        chain.doFilter(req, resp);

    }

    @Override
    public void destroy() {
        // do nothing
    }

    private void respWriter(HttpServletResponse resp, Result result) throws IOException {
        resp.getWriter().print(JSON.toJSONString(result));
    }

    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 获取到多个ip时取第一个作为客户端真实ip
        if (StringUtils.isNotEmpty(ip) && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            if (ArrayUtils.isNotEmpty(ipArray)) {
                ip = ipArray[0];
            }
        }
        return ip;
    }
}
